<?php

class DefaultController extends Controller
{
	public function actionIndex()
	{
		$cs = Yii::app()->getClientScript();
		$cs->registerScriptFile($this->module->assetsUrl.'/js/webcam.min.js');
		$this->render('index');
	}

	public function actionGetPhoto()
	{
		$allowed = false;
		if (Yii::app()->request->isAjaxRequest)
		{
			if(isset($_GET['option']) && isset($_FILES['webcam']))
			{
				$allowed = true;
				$imgPath = $this->module->facial->uploadPreview($_FILES['webcam']['tmp_name'], $_GET['option'].'.png');
				switch ($_GET['option'])
				{
					case 'facial':
						$this->requestFacial($imgPath);
						break;
					case 'qr':
						$this->requestQR($imgPath);
						break;
					default:
						$allowed = false;
				}
				if ($allowed)
				{
					unlink($imgPath);
					Yii::app()->end();
				}
			}
		}
		throw new CHttpException(403,Yii::t('yii', 'You are not authorized to perform this action.'));
	}

	public function actionConfirm()
	{
		$allowed = false;
		if (Yii::app()->request->isAjaxRequest)
		{
			if(isset($_GET['confirm']))
			{
				$allowed = true;
				switch ($_GET['confirm']) {
					case 'yes':
						$allowed = $this->requestConfirm();
						break;
					case 'no':
						$allowed = $this->requestCancel();
						break;
					default:
						$allowed = false;
				}
				if ($allowed)
				{
					Yii::app()->end();
				}
			}
		}
		throw new CHttpException(403,Yii::t('yii', 'You are not authorized to perform this action.'));
	}

	public function requestFacial($imgPath)
	{
		$answer = array();
		$error = true;
		$pyfacesPath = $this->module->facial->pyfacesPath;
		$galleryPath = $this->module->facial->galleryPath;
		$cmd = "python $pyfacesPath $imgPath $galleryPath 6 .3";
		exec($cmd, $r);
		$l = $r[count($r)-2];
		if (preg_match("/^matches/", $l))
		{
			if (preg_match("/(\d+)_\d+\.png/", $l, $m))
			{
				$user_id = $m[1];
				$model = Profesores::model()->findByPk($user_id);
				if ($model !== null)
				{
					$fullname = $model->id0->profile->fullname;
					$error = false;
					$answer['details'] = 'Reconocimiento facial realizado.';
				}
				else
					$answer['details'] = 'No es un profesor.';
			}
		}
		else
			$answer['details'] = 'No se pudo reconocer el rostro.';
		$answer['error'] = $error;
		if (!$error)
		{
			$answer['user_id'] = $user_id;
			$answer['fullname'] = $fullname;
		}
		echo CJSON::encode($answer);
	}

	public function requestQR($imgPath)
	{
		$answer = array();
		$error = true;
		$text = $this->module->qr->decrypt($imgPath);
		if ($text == false)
		{
			$answer['details'] = 'No se pudo leer el código QR o el código no es válido.';
		}
		else
		{
			$text = CJSON::decode($text);
			$user_id = $text['user_id'];
			$model = Profesores::model()->findByPk($user_id);
			if ($model !== null)
			{
				$fullname = $model->id0->profile->fullname;
				$error = false;
				$answer['details'] = 'Lectura de código QR finalizada.';
			}
			else
				$answer['details'] = 'El usuario identificado no es un profesor.';
		}
		$answer['error'] = $error;
		if (!$error)
		{
			$answer['user_id'] = $user_id;
			$answer['fullname'] = $fullname;
		}
		echo CJSON::encode($answer);
	}

	public function requestConfirm()
	{

		if (!isset($_POST['user_id']) || !isset($_POST['tipo_marcacion'])) return false;
		

		$fechaAhora = new CDbExpression('NOW()'); 
		$model = new Marcaciones;
	    $model->id = $_POST['user_id']; //'2014-05-27';
		//$model->tiempo = $fechaAhora;
	   

		switch ($_POST['tipo_marcacion']) {
			case 'entrada':
				$model->tipo_marcacion='E';
				break;
			case 'salida':
				$model->tipo_marcacion='S';
				break;
			default:
				return false;
				break;
		}

		if($model->save()){
			
			$model->refresh();
			$date = date("H:i:s", strtotime($model->tiempo));
			$answer = '<strong>¡Confirmado!</strong><br>Hora: '.$date;
			echo $answer;
			//echo Yii::app()->marcaciones->lastInsertID;
			return true;
		}
		return false;
	}

	public function requestCancel()
	{
		$answer = 'Cancelado.';
		echo $answer;
		return true;
	}
}